<?php

namespace App\Admin\Extensions;

use Encore\Admin\Grid\Exporters\AbstractExporter;
use Maatwebsite\Excel\Facades\Excel;

class ExcelExpoter extends AbstractExporter
{   
    protected $file_name;
    protected $sheet_name;
    protected $head = [];
    protected $body = [];

    public function setAttr($file_name, $sheet_name, $head, $body){
        $this->file_name  = $file_name;
        $this->sheet_name = $sheet_name;
        $this->head = $head;
        $this->body = $body;
    }

    public function export()
    {
        $file_name = $this->file_name.'-'.date('YmdHis');
        Excel::create($file_name, function($excel) {

            $excel->sheet($this->sheet_name, function($sheet) {

                // 这段逻辑是从表格数据中取出需要导出的字段
                $head = $this->head;
                $body = $this->body;

                $bodyRows = collect($this->getData())->map(function ($item)use($body) {
                    foreach ($body as $keyName){
                        $arr[] = array_get($item, $keyName);
                    }
                    return $arr;
                });
                $rows = collect([$head])->merge($bodyRows);

//                $sheet->cell('F', function($cell) {
//
//                    // manipulate the cell
//                    $cell->setValue('data1');
//
//                });

                $sheet->rows($rows);

            });

        })->export('xls');
    }
}